package com.heima.behavior.interceptor;


import com.zhentao.model.pojo.ApUser;
import com.zhentao.utils.common.AppJwtUtil;
import com.zhentao.utils.common.AppThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AppTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        Object userId = claimsBody.get("id");

        if(userId != null){
            //存入到当前线程中
            ApUser apUser = new ApUser();
            apUser.setId((Integer) userId);
            AppThreadLocalUtil.setUser(apUser);

        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppThreadLocalUtil.clear();
    }
}
